var valid;

$(function(){
	render_top_bar();
	render_page_header();
	render_normal_avatar();
	switch( settings_type ) {
		case "basics":
			valid = {
				'email': false, 
				'fullname': false
			};
			init_basics_page();
			break;
		case "avatar":
			init_avatar_page();
			break;
		case "password":
			valid = {
				'oldpsw': false, 
				'newpsw': false, 
				'newpswagain': false
			};
			init_password_page();
			break;
		case "privacy":
			break;
	}
});

function render_page_header() {
	var header = $("#page-header");
	var body = "<h2><img height = 30 src='" + session_user_info['avatar'] + "'/>";
	body += session_user_info['username'] + "'s settings</h2>";
	header.html( body );
}

function render_nav( focus ) {
	var nav = $("#settings-nav");
	nav.html( '<div id="settings-nav-inner">' );
	nav.append( '<a href="settings_basics.php"><div class="nav-item" id="nav_basics">Basics</div></a>' );
	nav.append( '<a href="settings_password.php"><div class="nav-item" id="nav_password">Password</div></a>' );
	nav.append( '<a href="settings_avatar.php"><div class="nav-item" id="nav_avatar">Avatar</div></a>' );
	nav.append( '<a href="settings_about.php"><div class="nav-item" id="nav_about">About us</div></a>' );
	nav.append( '</div>' );
	nav.ready( function() {
		var s = $(focus);
		s.addClass( "selected" );
	} );
}

function render_normal_avatar() {
	$('#avatar-normal').html("<img src='" + session_user_info['avatar'] + "'/>");
}

function add_input_tips( selector, message, voffset ) {
        var newdiv;
        if( voffset != undefined ) {
            newdiv = "<div class='input-tip rounded tips' style='left: " + voffset.h + "px; top: " + voffset.v + "px;'>" + message + "</div>";
        } else {
            newdiv = "<div class='input-tip rounded tips'>" + message + "</div>";
        }
	
	selector.parent().find( ".tips" ).remove();
	selector.parent().append( newdiv );
	selector.focusout(function() {
		selector.parent().find( ".input-tip" ).remove();
	});
}

function add_input_checking( selector, callback ) {
	var newdiv = "<img class='tips' style='position:absolute; top: 5px; left: 295px;' src='./img/ajax-loader.gif' />";
	selector.parent().find( ".tips" ).remove();
	selector.parent().append( newdiv );
	if( callback ) {
		callback();
	}
}

function add_input_error_message( selector, message ) {
	var newdiv = "<div class='input-error rounded tips'>" + message + "</div>";
	selector.parent().find( ".tips" ).remove();
	selector.parent().append( newdiv );
}

function add_input_ok( selector ) {
	var newdiv = "<img class='tips' style='position:absolute; top: 5px; left: 280px;' src='./img/valid.png' />";
	selector.parent().find( ".tips" ).remove();
	selector.parent().append( newdiv );
}

function check_old_password( callback0, callback1 ) {
	var selector = $("#old-password");
	add_input_checking( selector );
	$.ziPOST( "checkpsw", {
		password: selector.val()
	}, function( r ) {
		if( r ) {
			add_input_ok( selector );
			if( callback0 ) {
				callback0();
			}
			valid.oldpsw = true;
		} else {
			add_input_error_message( selector, "Wrong password" );
			if( callback1 ) {
				callback1();
			}
			valid.oldpsw = false;
		}
	});
}

function check_new_password( ) {
	var selector = $("#new-password");
	add_input_checking( selector );
	if( selector.val().length < 6 ) {
		add_input_error_message( selector, "New password is too weak" );
		valid.newpsw = false;
		return false;
	} else {
		add_input_ok( selector );
		if( $("#new-password-again").val() != "" ) {
			check_new_password_again();
		}
		valid.newpsw = true;
		return true;
	}
}

function check_new_password_again( ) {
	var new_psw = $("#new-password");
	var new_again = $("#new-password-again");
	add_input_checking( new_again );
	if( new_again.val().length < 4 ) {
		add_input_error_message( new_again, "Invalid password format" );
		valid.newpswagain = false;
		return false;
	} else if( new_psw.val() != new_again.val() ) {
		add_input_error_message( new_again, "Please re-check your input" );
		valid.newpswagain = false;
		return false;
	} else {
		add_input_ok( new_again );
		valid.newpswagain = true;
		return true;
	}
}
function init_basics_page(){
	$('#settings-main-content-inner').css('opacity', '0.5');
	$.ziGET("getUser", {uid: session_user_info['uid']}, function( r ){
		$('#settings-main-content-inner').css('opacity', '1');
		session_user_info = r[0];
		if( session_user_info['fullname'] != "" ) {
			$('#input-fullname').val( session_user_info['fullname'] );
			valid.fullname = true;
		}
		$('#input-birthday').val( session_user_info['birthday'] );
		if( session_user_info['email'] != "" ) {
			$('#input-email').val( session_user_info['email'] );
			valid.email = true;
		}
		$('#input-blog').val( session_user_info['blog'] );
		$('#input-description').val( session_user_info['description'] );
	
		switch( session_user_info['gender'] ) {
			case "male":
				$('#male').attr( 'current', 'true' );
				break;
			case "female":
				$('#female').attr( 'current', 'true' );
				break;
			case "x":
			default:
				$('#x').attr( 'current', 'true' );
				break;
		}
	
		$('.gender').click( function() {
			$('.gender').attr( 'current', 'false' );
			$(this).attr('current', 'true');
		});
	
		$('#input-fullname').focusin( function() {
			add_input_tips( $(this), "Your real full name(first/last name), or any kind of fancy name you like :). At least 2 characters."  );
		});
		$('#input-birthday').focusin( function() {
			add_input_tips( $(this), "YYYY/MM/DD"  );
		});
		$('#input-blog').focusin( function() {
			add_input_tips( $(this), "Put your blog (or facebook, twitter, renren, etc.) to introduce others to your personal page"  );
		});
		$('#input-email').focusin( function() {
			add_input_tips( $(this), "Wormhole may contact you with this email address."  );
		});
		$('#input-description').focusin( function() {
			add_input_tips( $(this), "Write a short description about yourself."  );
		});
	
		$('#input-fullname').focusout( function() {
			if( $(this).val().length < 2 ) {
				add_input_error_message( $(this), "At least 2 characters."  );
				valid.fullname = false;
			} else {
				add_input_ok( $(this) );
				valid.fullname = true;
			}
		});
		$('#input-birthday').focusout( function() {
			if( $(this).val().length < 2 ) {
				add_input_error_message( $(this), "At least 2 characters."  );
			} else {
				add_input_ok( $(this) );
			}
		});
		$('#input-blog').focusout( function() {
			add_input_tips( $(this), "Put your blog (or facebook, twitter, renren, etc.) to introduce others to your personal page"  );
		});
		$('#input-email').focusout( function() {
			if( ! /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i.test( $(this).val() ) ) {
				add_input_error_message( $(this), "Wrong email format"  );
			} else {
				add_input_checking( $(this) );
				if( session_user_info['email'] == $(this).val() ) {
					add_input_ok( $(this) );
					valid.email = true;
					return;
				}
				$.ziGET("checkfield", {
					'field': "email", 
					'data': $(this).val()
					}, function( r ){
					if( r == 1) {
						add_input_ok( $('#input-email') );
						valid.email = true;
					} else {
						add_input_error_message( $('#input-email'), "Email has been used!"  );
						valid.email = false;
					}
				});
			}
		});
		$('#input-description').focusout( function() {
			add_input_tips( $(this), "Write a short description about yourself."  );
		});
	
		$('#settings-save').click( function() {
			if( $(this).hasClass('disabled') ) {
				return;
			}
			$(this).addClass('disabled');
			$(this).html("Saving...");
			if( !valid.email ) {
				$(this).html("Save");
				$(this).removeClass('disabled');
				alert("Re-check your email");
				return;
			}
			if( !valid.fullname ) {
				$(this).html("Save");
				$(this).removeClass('disabled');
				add_input_error_message( $('#input-birthday'), "At least 2 characters."  );
				alert("Re-check your fullname (too short?)");
				return;
			}
			$.ziGET( 
				"update_settings", 
				{
					fullname: $('#input-fullname').val(),
					email: $("#input-email").val(),
					blog: $("#input-blog").val(),
					description: $("#input-description").val(),
					birthday: $("#input-birthday").val(),
					gender: $('.gender[current=true]').attr("id")
				}, 
				function( r ) {
					if( r ) {
						alert("Your have successfully changed your basic profile!");
					}
					location.reload();
				});
		});
	});

}


function init_password_page(){
	$('#old-password').focusout( function(){
		check_old_password();
	});
	$('#new-password').focusout( function() {
		check_new_password();
	});
	$('#new-password-again').focusout( function() {
		check_new_password_again();
	});
	$('#old-password').focusin( function() {
		add_input_tips( $(this), "Your current password"  );
	});
	$('#new-password').focusin( function() {
		add_input_tips( $(this), "A password should consist of 4 ~ 30 ASCII letters"  );
	});
	$('#new-password-again').focusin( function() {
		add_input_tips( $(this), "Please type your new password again"  );
	});
	$('#settings-save').click( function() {
		if( $(this).hasClass('disabled') ) {
			return;
		}
		$(this).addClass('disabled');
		$(this).html("Saving...");
		if( !valid.oldpsw ) {
			$(this).html("Save");
			$(this).removeClass('disabled');
			alert("Your current password is invalid!");
			return;
		}
		if( !valid.newpswagain ) {
			$(this).html("Save");
			$(this).removeClass('disabled');
			check_new_password_again( );
			return;
		}
		$.ziPOST( 
			"updatefield", 
			{
				field: "password",
				password: $("#old-password").val(),
				newval:  $('#new-password').val()
			}, 
			function( r ) {
				if( r == 1 ) {
					alert("Your have successfully changed your password!");
				}
				location.reload();
			});
	});
}

function init_avatar_page() {
	$("#avatar-url").val( session_user_info['avatar'] );
	$("#avatar-change").click( function() {
		$("#avatar-change").attr("disabled", "disabled");
		var url = $("#avatar-url");
		change_avatar( url.val(), function(){
			location.reload();
		} );
	});
	$("#avatar-url").focusin( function() {
		add_input_tips( $(this), "Please copy the image URL (right click any images online and copy) to the following blank; uploading funcions will be finished soon.", {h:202, v:80}  );
	});
}

function change_avatar( url, callback ) {
	$.ziPOST('updatefield', 
	{
		'field': 'avatar', 
		'newval': url
	},
	function(r) {
		if( r > 0 )
			callback();
		else
			alert("Something is wrong!");
	});			
}

